import {Button, Descriptions, Divider, Drawer, Image, message, Popconfirm, Space, Tag} from 'antd';
import React, {useState} from 'react';
import {downloadFileUrl} from "@/services/system/file";
import {
  addQuestionOptionAPI, deleteQuestionOptionAPI,
  getQuestionOptionsAPI,
  updateQuestionOptionAPI
} from "@/pages/question/question-manager/service";
import {DiffOutlined, EditOutlined, PlusOutlined} from "@ant-design/icons";
import {DeleteOutline} from "antd-mobile-icons";
import QuestionOptionForm from "@/pages/question/question-manager/components/QuestionOptionForm";

interface QuestionDetailProps {
  visible: boolean;
  onClose: () => void;
  question: API.IQuestion;
}

const QuestionDetail: React.FC<QuestionDetailProps> = ({visible, onClose, question}) => {

  const [questionOptions, setQuestionOptions] = useState<API.IQuestionOption[]>([]);

  const fetchQuestionOptions = async () => {
    if (!question || !question?.id) {
      message.error('题目ID不能为空')
      return;
    }
    const {data} = await getQuestionOptionsAPI(question?.id);
    if (data) {
      setQuestionOptions(data);
    }
  };

  const getQuestionTypeText = (type: string) => {
    switch (type) {
      case '1':
        return '单选题';
      case '2':
        return '多选题';
      case '3':
        return '判断题';
      default:
        return '未知类型';
    }
  };
  const getDifficultyText = (difficulty: string) => {
    switch (difficulty) {
      case '1':
        return '简单';
      case '2':
        return '中等';
      case '3':
        return '困难';
      default:
        return '未知';
    }
  };


  return (
    <Drawer
      title="题目详情"
      width={860}
      onClose={onClose}
      visible={visible}
      afterOpenChange={async (open) => {
        if (open) {
          await fetchQuestionOptions()
        }
      }}
    >
      <Descriptions column={2} bordered>
        <Descriptions.Item label="题目ID">{question?.id}</Descriptions.Item>
        <Descriptions.Item label="题目类型">{question?.questionTypeName}</Descriptions.Item>
        <Descriptions.Item
          label="驾照类型">{`${question?.licenseTypeName}(${question?.licenseTypeCode})`}</Descriptions.Item>
        <Descriptions.Item label="所属科目">{question?.courseSubjectName}</Descriptions.Item>
        <Descriptions.Item label="题目类型">{getQuestionTypeText(question?.questionType || '')}</Descriptions.Item>
        <Descriptions.Item label="题目难度">
          <Tag color={question?.difficulty === '3' ? 'red' : question?.difficulty === '2' ? 'orange' : 'green'}>
            {getDifficultyText(question?.difficulty || '')}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="题目内容" span={2}>{question?.content}</Descriptions.Item>
        <Descriptions.Item label="题目考点" span={2}>{question?.keyPoint}</Descriptions.Item>
        <Descriptions.Item label="题目解析" span={2}>{question?.explanation}</Descriptions.Item>
        <Descriptions.Item label="是否新规题">
          <Tag color={question?.isNewRule === '0' ? 'green' : 'default'}>
            {question?.isNewRule === '0' ? '是' : '否'}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="是否热门题">
          <Tag color={question?.isHot === '0' ? 'red' : 'default'}>
            {question?.isHot === '0' ? '是' : '否'}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="状态">
          <Tag color={question?.status === '0' ? 'green' : 'red'}>
            {question?.status === '0' ? '启用' : '禁用'}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="创建时间">{question?.createdAt}</Descriptions.Item>
      </Descriptions>


      {question?.contentImage && (
        <>
          <Divider orientation={"left"}>题目图片</Divider>
          <Image width={160} src={downloadFileUrl(question?.contentImage)}/>
        </>
      )}

      <div style={{marginTop: 24}}>
        <Divider orientation={"left"}>
          题目选项

          <QuestionOptionForm
            key="addOption"
            formType="create"
            onFinish={async (values) => {
              const {data} = await addQuestionOptionAPI(values as any);
              if (data) {
                message.success('选项添加成功');
                await fetchQuestionOptions();
              }
              return data;
            }}
            questionId={question?.id || ''}
            trigger={<Button size={'small'} type={'link'} icon={<DiffOutlined/>}>新增选项</Button>}
          />
        </Divider>
        {questionOptions.map(option => (
          <div key={option.id} style={{
            marginBottom: 8,
            padding: 8,
            borderRadius: 6,
            background: option.isCorrect === '0' ? '#f6ffed' : '#fff',
            border: `1px solid ${option.isCorrect === '0' ? '#b7eb8f' : '#d9d9d9'}`
          }}>
            <strong>{option.optionCode}.</strong> {option.content}
            {option.contentImage &&
              <Image width={100} src={downloadFileUrl(option.contentImage)} style={{marginLeft: 8}}/>}
            {option.isCorrect === '0' ? <Tag color="success" style={{marginLeft: 8}}>正确答案</Tag> : ''}
            <Space size={'small'} style={{marginLeft: 8}}>
              <QuestionOptionForm
                key="addOption"
                formType="edit"
                initialValues={option}
                onFinish={async (values) => {
                  const {data} = await updateQuestionOptionAPI({...values, id: option?.id});
                  if (data) {
                    message.success('修改成功');
                    await fetchQuestionOptions();
                  }
                  return data;
                }}
                questionId={question.id || ''}
                trigger={<Button size={'small'} type={'text'} icon={<EditOutlined/>}/>}
              />
              <Popconfirm
                title={"确认删除此选项吗"}
                onConfirm={async () => {
                  const {data} = await deleteQuestionOptionAPI(option?.id || '');
                  if (data) {
                    message.success('删除成功');
                    await fetchQuestionOptions();
                  }
                }}
              >
                <Button danger size={'small'} type={'text'} icon={<DeleteOutline/>}/>
              </Popconfirm>
            </Space>
          </div>
        ))}
      </div>
    </Drawer>
  )
    ;
};

export default QuestionDetail;
